package com.ruoyi.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.project.domain.dto.DingdanDTO;
import com.ruoyi.project.mapper.DingdanMapper;
import com.ruoyi.project.domain.entity.Dingdan;
import com.ruoyi.project.service.DingdanService;
import org.springframework.stereotype.Service;

import lombok.AllArgsConstructor;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 订单(Dingdan)表服务实现类
 *
 * @author yanweichao
 * @since 2025-06-20
 */
@Service
@AllArgsConstructor
public class DingdanServiceImpl extends ServiceImpl<DingdanMapper, Dingdan> implements DingdanService {

    protected LambdaQueryWrapper<Dingdan> queryWrapper(DingdanDTO param) {
        return new LambdaQueryWrapper<Dingdan>()
                .and(StrUtil.isNotEmpty(param.getKeyword()), q -> q
                    .likeRight(Dingdan::getDdzh, param.getKeyword())
                    .or().likeRight(Dingdan::getYwdh, param.getKeyword()))
                .orderByDesc(Dingdan::getId);
    }

    @Override
    public Page<Dingdan> listPage(Page<Dingdan> page, DingdanDTO param) {
        return this.page(page, queryWrapper(param));
    }

    @Override
    public List<Dingdan> queryList(DingdanDTO param) {
        return this.list(queryWrapper(param));
    }

    @Override
    public DingdanDTO getDtoById(Integer id) {
        Dingdan entity = this.getById(id);
        DingdanDTO dto = DingdanDTO.of(entity);
        if (StrUtil.isNotEmpty(entity.getPtcp())) {
            List<DingdanDTO.Ptcp> list = JSONUtil.toList(entity.getPtcp(), DingdanDTO.Ptcp.class);
            dto.setPtcpList(list);
            dto.setYsyqList(StrUtil.split(entity.getYsyq(), ","));
        }
        return dto;
    }

    @Override
    public Dingdan genNo() {
        Dingdan data = new Dingdan();
        String prefix = "D00" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyMMdd"));
        String no = Optional.ofNullable(this.getBaseMapper().getMaxNo(prefix)).orElse("0");
        data.setYwdh(prefix + StrUtil.fillBefore(String.valueOf(Integer.parseInt(no) + 1), '0', 3));
        prefix = "Z00" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyMMdd"));
        no = Optional.ofNullable(this.getBaseMapper().getZongMaxNo(prefix)).orElse("0");
        data.setDdzh(prefix + StrUtil.fillBefore(String.valueOf(Integer.parseInt(no) + 1), '0', 3));
        return data;
    }

    @Override
    public boolean saveOrUpdate(DingdanDTO param) {
        this.getBaseMapper().saveZongNo(param.getDdzh());
        return param.isNew() ? this.save(param) : this.updateById(param);
    }
}
